package com.android.questions.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.android.base.util.ActivityClickUtil;
import com.android.base.util.DQLog;
import com.android.base.util.DisplayUtil;
import com.android.base.util.ToastUtil;
import com.android.questions.R;
import com.android.questions.config.AppConfig;
import com.android.questions.config.LoginConfig;
import com.android.questions.databinding.DialogCashCowBinding;
import com.android.questions.ui.activity.LoginActivity;
import com.android.questions.ui.adapter.CowAdapter;
import com.android.questions.util.sound.MediaBackManager;
import com.dq.ad.AdManager;
import com.dq.ad.UMManager;
import com.hx.currency.HXCurrencySDK;
import com.hx.currency.data.qa.api.QAIncomeConfigResp;
import com.hx.currency.data.qa.api.QAIncomeResp;
import com.hx.currency.data.qa.model.QAIncome;
import com.qq.e.o.ads.v2.error.AdError;
import com.qq.e.o.data.HttpUtil;
import com.qq.e.o.utils.JsonUtil;

import java.util.List;

/**
 * FileName: DialogCashCow
 * Author: admin
 * Date: 2022/1/23 14:33
 * Description:
 */
public class DialogCashCow extends Dialog implements View.OnClickListener {

    private DialogCashCowBinding cowBinding;
    private OnClickLister clickLister;
    private final Activity activity;
    private CowAdapter cowAdapter;
    private boolean isReward;

    public DialogCashCow(Activity act) {
        super(act, R.style.dialog_loading);
        this.activity = act;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cowBinding = DialogCashCowBinding.inflate(activity.getLayoutInflater());
        setContentView(cowBinding.getRoot());

        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = DisplayUtil.getScreenWidth(activity);
        lp.height = DisplayUtil.getScreenHeight(activity);
        getWindow().setAttributes(lp);

        getWindow().setWindowAnimations(R.style.dialog_answer_correct);

        setCancelable(false);
        setCanceledOnTouchOutside(false);

        initView();
    }

    private void initView() {
        ActivityClickUtil.getInstance().clear();
        UMManager.onEvent(UMManager.Event.open_Cashcow);
        getCowConfig();

        cowAdapter = new CowAdapter();
        cowBinding.rvCow.setAdapter(cowAdapter);
        cowAdapter.setClickLister(new CowAdapter.OnItemChildClickLister() {
            @Override
            public void onWithdrawal(QAIncome item) {
                if (TextUtils.isEmpty(LoginConfig.getUserOpenId())) {
                    LoginActivity.startAct(activity, LoginActivity.TYPE_BIND, null);
                } else {
                    watchVideo(item);
                }
            }

            @Override
            public void onIncrease() {
                UMManager.onEvent(UMManager.Event.accelerate_Cashcow);
                if (AppConfig.hasNoAd()) {
                    AppConfig.showNoAdToast(activity);
                    getCowConfig();
                } else {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).pause();
                    }
                    AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                        @Override
                        public void onClosed(String orderId) {
                            if (AppConfig.getBackMusic()) {
                                MediaBackManager.getInstance(activity).start();
                            }
                            getCowConfig();
                        }

                        @Override
                        public void onReward() {

                        }

                        @Override
                        public void onShow(double ecpm) {
                        }

                        @Override
                        public void onFailed(int i, AdError adError) {
                            if (AppConfig.getBackMusic()) {
                                MediaBackManager.getInstance(activity).start();
                            }
                            getCowConfig();
                        }

                        @Override
                        public void onTimeout() {
                            if (AppConfig.getBackMusic()) {
                                MediaBackManager.getInstance(activity).start();
                            }
                            getCowConfig();
                        }
                    });
                }
            }
        });

        cowBinding.tvTodayPeople.setText(AppConfig.getTodayPeople() + "人");
        cowBinding.ivClose.setOnClickListener(this);
        cowBinding.lcIntroduce.setOnClickListener(this);
    }

    private void watchVideo(QAIncome item) {
        isReward = false;
        if (AppConfig.hasNoAd()) {
            getEarnings(item);
        } else {
            if (AppConfig.getBackMusic()) {
                MediaBackManager.getInstance(activity).pause();
            }
            AdManager.getInstance().showRewardVideoAD("", activity, new AdManager.OnRewardVideoADListener() {
                @Override
                public void onClosed(String orderId) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    if (isReward) {
                        getEarnings(item);
                    } else {
                        ToastUtil.showShortToast(activity, "未完整观看视频，提现失败");
                    }
                }

                @Override
                public void onReward() {
                    isReward = true;
                }

                @Override
                public void onShow(double ecpm) {
                }

                @Override
                public void onFailed(int i, AdError adError) {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    getEarnings(item);
                }

                @Override
                public void onTimeout() {
                    if (AppConfig.getBackMusic()) {
                        MediaBackManager.getInstance(activity).start();
                    }
                    getEarnings(item);
                }
            });
        }
    }

    private void getEarnings(QAIncome item) {
        DQLog.e("开始收益分红提现");
        HXCurrencySDK.getInstance().qaIncomeReq(item.getIid(), new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("获取收益分红成功:" + response);
                if (activity.isFinishing()) {
                    return;
                }
                QAIncomeResp qaIncomeResp = JsonUtil.parseObject(response, QAIncomeResp.class);
                int errorCode = qaIncomeResp.getErrorCode();
                if (errorCode == 0) {
                    UMManager.onEvent(UMManager.Event.receive_Cashcow);
                    withdrawalSuccess(false, item.getSa());
                } else if (errorCode == 10025) {
                    new DialogWithError(activity).setType(DialogWithError.TYPE_QUEUE).show();
                } else if (errorCode == 10026) {
                    withdrawalSuccess(true, item.getSa());
                } else if (errorCode == 10028) {
                    new DialogWithError(activity).show();
                } else {
                    ToastUtil.showShortToastCenter(activity, qaIncomeResp.getErrorMessage());
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("获取收益分红异常：" + throwable.toString());
                ToastUtil.showShortToastCenter(activity, "网络异常");
            }
        });
    }

    private void withdrawalSuccess(boolean isQueue, double rat) {
        AppConfig.setCashCow(AppConfig.getCashCow() - rat);
        getCowConfig();
        int remainWithdrawalTimes = AppConfig.getRemainWithdrawalTimes();
        if (remainWithdrawalTimes >= 1) {
            AppConfig.setRemainWithdrawalTimes(remainWithdrawalTimes - 1);
        }
        new DialogWithdrawalSuccess(activity).setCash(rat).setQueue(isQueue).setClickLister(new DialogWithdrawalSuccess.OnClickLister() {
            @Override
            public void onWithdrawal() {
                // 继续赚钱
            }
        }).show();
    }

    public DialogCashCow setClickLister(OnClickLister lister) {
        this.clickLister = lister;
        return this;
    }

    @Override
    public void onClick(View v) {
        if (ActivityClickUtil.getInstance().isFastClick()) {
            //防止用户快速点击
            return;
        }
        dismiss();
        if (v.getId() == R.id.lc_introduce) {
            if (clickLister != null) {
                clickLister.onIntroduce();
            }
        }
    }

    private void getCowConfig() {
        DQLog.e("开始获取收益分红列表");
        HXCurrencySDK.getInstance().getQAIncomeConfig(new HttpUtil.HttpUtilCallback() {
            @Override
            public void onSuccess(int i, String response) {
                DQLog.e("获取收益分红列表成功:" + response);
                QAIncomeConfigResp qaIncomeConfigResp = JsonUtil.parseObject(response, QAIncomeConfigResp.class);
                if (qaIncomeConfigResp != null) {
                    if (qaIncomeConfigResp.getErrorCode() == 0) {
                        updateUI(qaIncomeConfigResp.getIl());
                    } else {
                        DQLog.e("获取收益分红异常：" + qaIncomeConfigResp.getErrorMessage());
                    }
                } else {
                    DQLog.e("获取收益分红异常");
                    ToastUtil.showShortToast(activity, "数据未配置");
                }
            }

            @Override
            public void onFailed(int i, Throwable throwable) {
                DQLog.e("获取收益分红列表异常：" + throwable.toString());
                ToastUtil.showShortToast(activity, "网络异常");
            }
        });
    }

    private void updateUI(List<QAIncome> list) {
        cowAdapter.setList(list);
        cowAdapter.notifyDataSetChanged();
    }

    public interface OnClickLister {
        void onIntroduce();
    }
}